package com.sharemarking.system.controller;

import com.sharemarking.system.dto.Page;
import com.sharemarking.system.dto.personManagement.PersonListDto;
import com.sharemarking.system.mapper.ExcelImportMapper;
import com.sharemarking.system.mapper.OrderMapper;
import com.sharemarking.system.mapper.OrgVerifyMapper;
import com.sharemarking.wa.common.entity.Channel;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dxy
 */
@Controller
@RequestMapping("system/excelImport")
public class ExcelImportController {

    @Autowired
    private ExcelImportMapper excelImportMapper;
    @Autowired
    private OrgVerifyMapper om;
    @Autowired
    private HttpServletResponse response;

    /**
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping("indexcf")
    @PreAuthorize("hasPermission('base','all')")
    public String indexcf(HttpServletRequest request, Model model) {
        String id = request.getParameter("orgId");
        if(!StringUtils.isEmpty(id)){
            model.addAttribute("cflist",excelImportMapper.getPwExcelInfo(Integer.parseInt(id)));
        }
        model.addAttribute("orgList", excelImportMapper.getProductWasteOrgList());
        return "excelImport/indexcf";
    }

    /**
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping("indexjy")
    @PreAuthorize("hasPermission('base','all')")
    public String indexjy(HttpServletRequest request, Model model) {
        String id = request.getParameter("orgId");
        if(!StringUtils.isEmpty(id)){
            model.addAttribute("jylist",excelImportMapper.getJyExcelInfo(Integer.parseInt(id)));

        }
        model.addAttribute("orgList", excelImportMapper.getManagementOrgList());
        return "excelImport/indexjy";
    }

    /**
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping("indexys")
    @PreAuthorize("hasPermission('base','all')")
    public String indexys(HttpServletRequest request, Model model) {
        String id = request.getParameter("orgId");
        if(!StringUtils.isEmpty(id)){
            model.addAttribute("yslist",excelImportMapper.getYsExcelInfo(Integer.parseInt(id)));
        }
        model.addAttribute("orgList", excelImportMapper.getTransportOrgList());
        return "excelImport/indexys";
    }

    /**
     * 导出
     */
    @GetMapping("export")
    @PreAuthorize("hasPermission('base','all')")
    public void export(Integer orgId,Integer type) throws IOException {
        List<String> titleList = new ArrayList<>();
        switch (type) {
            case 0:
                //产废导出
                titleList.add("日期#create_date");
                titleList.add("接收经营单位#manage_org_name");
                titleList.add("废物类别#waste_type_name");
                titleList.add("废物名称#waste_name");
                titleList.add("运输公司#transport_org_name");
                titleList.add("联单编号#code");
                titleList.add("平台发布数量t#weight");
                titleList.add("发布信息人员#send_org_member");
                titleList.add("确认接收数量t#receive_weight");
                excel(excelImportMapper.getPwExcelInfo(orgId),titleList,om.getNameByOrg(orgId)+"产废单位平台数据信息统计表");
                break;
            case 1:
                //经营导出
                titleList.add("日期#create_date");
                titleList.add("产废企业名称#manage_org_name");
                titleList.add("运输公司名称#transport_org_name");
                titleList.add("联单编号#code");
                titleList.add("废物类别#waste_type_name");
                titleList.add("废物名称#waste_name");
                titleList.add("平台发布数量t#weight");
                titleList.add("确认接收人员#receive_org_member_name");
                titleList.add("确认接收数量t#receive_weight");
                excel(excelImportMapper.getJyExcelInfo(orgId),titleList,om.getNameByOrg(orgId)+"经营单位平台数据信息统计表");
                break;
            case 2:
                //运输导出
                titleList.add("日期#create_date");
                titleList.add("产废企业名称#manage_org_name");
                titleList.add("经营单位名称#send_org_name");
                titleList.add("联单编号#code");
                titleList.add("废物类别#waste_type_name");
                titleList.add("废物名称#waste_name");
                titleList.add("调度人员#transport_org_member_name");
                titleList.add("司机姓名#driver_name");
                titleList.add("车牌号#car_id");
                titleList.add("车型#car_type");
                titleList.add("转移吨数t#receive_weight");
                excel(excelImportMapper.getYsExcelInfo(orgId),titleList,om.getNameByOrg(orgId)+"运输单位平台数据信息统计表");
                break;
        }
    }

    private void excel(List<Map<String, Object>> paramsMap,List<String> titleList,String fileName) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();//创建Excel工作簿对象
        HSSFSheet sheet = wb.createSheet("new sheet");//创建Excel工作表对象


        HSSFRow row = sheet.createRow((short) 0); //创建Excel工作表的行
        row.setHeight((short) 840);

        Cell cell = row.createCell((short) 0);
        cell.setCellValue(fileName); //设置Excel工作表的值

        //创建一个字体
        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 18);
        font.setFontName("宋体");

        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
        cell.setCellStyle(style);

        //合并单元格
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 8);
        sheet.addMergedRegion(region);

        HSSFRow rowOne = sheet.createRow((short) 1);
        int rowOneCount = 0;
        for (String s : titleList) {
            rowOne.createCell((short) rowOneCount).setCellValue(s.split("#")[0]);
            sheet.setColumnWidth((short) rowOneCount, (short) 4500);
            rowOneCount++;
        }

        int allRowCount = 2;
        for (Map<String,Object> map : paramsMap){
            HSSFRow dataRow = sheet.createRow((short) allRowCount);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                for (int i = 0; i < titleList.size(); i++) {
                    if (titleList.get(i).split("#")[1].equals(entry.getKey())) {
                        dataRow.createCell(i).setCellValue(String.valueOf(entry.getValue()));
                        continue;
                    }
                }
            }
            allRowCount++;
        }
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        byte[] b_iso88591 = fileName.getBytes("utf-8");
        fileName = new String(b_iso88591, "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
        OutputStream outputStream = response.getOutputStream();
        outputStream.flush();
        wb.write(outputStream);
        wb.close();
    }



}
